package io.seata.storage.service.impl;

import io.seata.common.dto.StorageDTO;
import io.seata.common.enums.RspStatusEnum;
import io.seata.common.exception.DefaultException;
import io.seata.common.response.ObjectResponse;
import io.seata.storage.entity.Storage;
import io.seata.storage.mapper.StorageMapper;
import io.seata.storage.service.StorageService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource;

/**
 * @author ZengRJ
 */
@Slf4j
@Service
public class StorageServiceImpl implements StorageService {

    @Resource
    private StorageMapper storageMapper;

    @Transactional
    @Override
    public ObjectResponse deduct(StorageDTO storageDTO) {
        log.info("开始扣减库存");
        ObjectResponse objectResponse = new ObjectResponse();
        try {
            Storage storage = new Storage();
            BeanUtils.copyProperties(storageDTO, storage);
            storageMapper.deduct(storage);
        } catch (Exception e) {
            throw new DefaultException("扣减库存失败，可能是库存不足！", e);
        }
        log.info("扣减库存成功");
        objectResponse.setStatus(RspStatusEnum.SUCCESS.getCode());
        objectResponse.setMessage(RspStatusEnum.SUCCESS.getMessage());
        return objectResponse;
    }
}
